package com.stxx.stiot2.mqtt;

import com.stxx.framwork.utils.StoreUtils;
import com.stxx.stiot2.event.dto.T2pMsg;
import com.stxx.stiot2.gateway.GatewayUtils;
import com.stxx.stiot2.gateway.face.GatewayServer;
import com.stxx.stiot2.service.GatewayService;
import com.stxx.stiot2.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.codec.MqttPublishMessage;
import org.dromara.mica.mqtt.codec.MqttQoS;
import org.dromara.mica.mqtt.core.server.event.IMqttMessageListener;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.event.EventBus;
import org.tio.core.ChannelContext;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class MqttServerMessageListener implements IMqttMessageListener {
    @Inject
    StoreUtils storeUtils;
    @Inject
    SysConfigService configService;
    @Inject
    GatewayService gatewayService;
    @Inject
    GatewayUtils gatewayUtils;

    @Override
    public void onMessage(ChannelContext context, String clientId, String topic, MqttQoS qoS, MqttPublishMessage message) {
        GatewayServer server = gatewayUtils.getGatewayByTopic(topic);
        if(server!=null){
            T2pMsg message2 = server.receive(topic,new String(message.getPayload()));
            EventBus.publish(message2);

        }
//        //TopicUtil.match()
//        //如果不匹配标准主题
//        if(!TopicUtil.match(Topics.topic(Topics.T2p.report),topic)){
//            //TODO 到自定义里进行解析
//            return;
//        }
//
//
//        String [] strs = topic.split("/");
//        String gatewayCode = strs[2];
//        String terminalCode = strs[3];
//        Gateway r = gatewayService.queryById(gatewayCode);
//        if(r == null) {
//            log.error("没有找到网关");
//        }
//        T2pMsg message2 = new T2pMsg();
//        message2.setGatewayCode(gatewayCode);
//        message2.setTerminalCode(terminalCode);
//        message2.setData(JSON.parseObject(new String(message.getPayload()), ReportData.class));
//        EventBus.publish(message2);
//        log.info("接收到消息：\n主题：" + topic + "\n消息：" + new String(message.getPayload()));
//        log.info("clientId:{} message:{} payload:{}", clientId, message, new String(message.getPayload(), StandardCharsets.UTF_8));
    }
}